package com.cswnode.Service.impl;

import com.cswnode.Dao.UserMapper;
import com.cswnode.Entity.User;
import com.cswnode.Service.UserService;
import com.cswnode.Util.CommunityUtil;
import com.cswnode.Util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author csw
 * @create 2020/9/19 20:25
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    public User findUserById(int userId){
        //return userMapper.selectById(userId);
        User user = UserCache(userId);
        if (user == null){
            user = userCacheLoading(userId);
        }
        return user;
    }

    @Override
    public int updateHeaderUrl(int userId, String HeaderUrl) {
        int result = userMapper.updateHeader(userId,HeaderUrl);
        userCacheRemove(userId);
        return result;
    }

    @Override
    public Map<String, String> updatePassword(int userId, String oldPassword, String newPassword) {
        Map<String,String> map = new HashMap<>();
        User user = findUserById(userId);
        String userPassword = CommunityUtil.MD5(oldPassword + user.getSalt());
        if (!userPassword.equals(user.getPassword())){
            map.put("passwordError","输入的密码错误！");
            return map;
        }
        String Password = CommunityUtil.MD5(newPassword + user.getSalt());
        int i = userMapper.updatePassword(userId, Password);
        if (i == 0 ){
            throw new RuntimeException("修改密码失败！");
        }
        userCacheRemove(userId);
        return map;
    }

    @Override
    public User findUserByName(String username) {
        return userMapper.selectByName(username);
    }

    //读取缓存信息
    private User UserCache(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        return (User) redisTemplate.opsForValue().get(userKey);
    }

    //加载缓存信息
    private User userCacheLoading(int userId){
        User user = userMapper.selectById(userId);
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.opsForValue().set(userKey,user,3600, TimeUnit.SECONDS);
        return user;
    }

    /**
     * 更改数据时清除缓存
     * @param userId
     */
    private void userCacheRemove(int userId){
        String userKey = RedisKeyUtil.getUserKey(userId);
        redisTemplate.delete(userKey);
    }



}
